package com.jyhz.author.service.service;

import com.jyhz.author.common.pojo.UserInfo;
import com.jyhz.author.common.utils.JwtUtils;
import com.jyhz.author.service.client.UserClient;
import com.jyhz.author.service.config.JwtProperties;
import com.jyhz.author.service.pojo.User;
import com.jyhz.common.dto.HttpResult;
import com.jyhz.common.util.HttpStatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

/**
 * @author hf
 * @create 2021-04-11 10:54
 */
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProperties;

    public String accredit(String username, String password) {
        //根据username和password查询user
        HttpResult result = userClient.getUserByUsernameAndPassword(username, password);
        //判断
        if(result.code!= HttpStatusCode.OK.getCode()){
            return null;
        }
        try {
            //jwtUtils生成jwt类型的token
            System.out.println(result.data);
            UserInfo userInfo = new UserInfo();
            LinkedHashMap<String,Object> data = (LinkedHashMap<String, Object>) result.data;
            userInfo.setId(Long.parseLong(data.get("id").toString()));
            userInfo.setUsername(data.get("username").toString());
            return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
